package cpu_cards_service

import (
	"encoding/json"
	"fmt"
	"heyzhima-yt-cpu/models"
	"heyzhima-yt-cpu/pkg/gredis"
	"heyzhima-yt-cpu/pkg/logging"
	"heyzhima-yt-cpu/pkg/setting"
	"heyzhima-yt-cpu/pkg/util"
	"heyzhima-yt-cpu/service/cache_service"
	"github.com/RNCryptor/RNCryptor-go"
)

type Cards struct {
	CardId         int
	Uid            string
	CardCode       string
	CardNum        string
	CardExpired    int
	CardType       string
	CardFunc       string
	CardDisabled   string
	CardDesc       string
	CardScan       string
	ZoneId         int
	BuildingId     int
	UserId         string
	RoomId         string
	AgentAccountId string
	AccountId      string
	LastUse        string
	CardIsCpu      string
	CardCpuSecret  string
	CreatedAt      string
	UpdatedAt      string
	DeletedAt      string
}



func (a *Cards) GetCardInfo(code string) ([]*models.Cards, error) {
	var cacheCards []*models.Cards

	cache := cache_service.Cards{CardCode: code}
	key := cache.GetCardKey()
	if gredis.Exists(key) {
		data, err := gredis.Get(key)
		if err != nil {
			logging.Info(err)
		} else {
			json.Unmarshal(data, &cacheCards)
			return cacheCards, nil
		}
	}

	cardsInfo, err := models.GetCardsInfo(code)
	if err != nil {
		return nil, err
	}

	gredis.Set(key, cardsInfo, 3600)
	return cardsInfo, nil
}

func (a *Cards) Update(CardId int,secret string,okey string) (bool, error) {
	return models.UpdateCard(CardId,secret,okey)
}

func (a *Cards) SendCard(card map[string]interface{}, adminId int)(bool ,error){
	fmt.Println("SendCard")
	fmt.Println(card)
	gateId ,err:= models.GetGatesBuildingsInfo(card["building_id"].(int64),card["zone_id"].(int))
	if err != nil {
		return false, err
	}
	printSlice(gateId)
	fmt.Println(gateId)
	if gateId == nil{
		logging.Info("切片是空的")
	}
	result := make(map[string]interface{})
	result["from"]=1
	result["card_id"]=card["cardId"]
	result["cardIsCpu"]=card["cardIsCpu"]
	result["cardCpuSecret"]=card["cardCpuSecret"]
	result["cardCode"]=card["cardCode"]
	result["cardExpired"]=card["cardExpired"]
	result["faceDetect"]="Y"
	result["created"]=util.CurrentTime()
	result["account_id"]=card["AccountId"]
	url:= setting.AppSetting.DeviceApiUrl + "/action/v3/registerCard"
	for _,v := range gateId {
		result["gate_id"]=v
		jsonData,err := json.Marshal(result)
		if err != nil {
			logging.Info(err)
		}
		deviceApiRequest(url, jsonData)
	}
    return true,err
}

func printSlice(x []int64){
	fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
}

func deviceApiRequest(url string,postData []byte){
	fmt.Println("deviceApiRequest")
	queries := map[string]string{
		"page": "2",
		"act":  "update",
	}
	m1 := make(map[string]interface{})
	err := json.Unmarshal(postData, &m1)
	if err != nil {
		logging.Info(err)
	}
	fmt.Println(m1)
	re,err1:=util.HttpPost(url,queries,m1)
	logging.Info(err1)
	fmt.Println(re)
}

func response(errCode int,msg string,res map[string]interface{},ret bool)([]byte){
	fmt.Println("response")
	retA := make(map[string]interface{})
	retA["errcode"] = errCode
	retA["msg"] = msg
	retA["timestamp"] = util.GetCurrentUnix()
	if len(res)>1 {
		jsonData,err := json.Marshal(res)
		if err != nil {
			logging.Info(err)
		}
		encrypted, _ := rncryptor.Encrypt(setting.AppSetting.ResponseKey, jsonData)
		fmt.Printf("encrypted: %v\n", string(encrypted))
		fmt.Println("A")
		// if you need to send the encrypted data across
		// the wire, you'll probably want to call
		// `base64.StdEncoding.EncodeToString(encrypted)`
		// to base64 the data rather than transmiting raw bytes

		//decrypted, _ := rncryptor.Decrypt(setting.AppSetting.ResponseKey, encrypted)
		//fmt.Printf("decrypted: %v\n", string(decrypted))
		var s string
		s+=string(encrypted)
		s+=string(util.GetCurrentUnix())
		s+=setting.AppSetting.ResponseKey

		bs := util.EncodeSHA1(s)
		fmt.Println(s)
		fmt.Println("B")
		fmt.Printf("%x\n", bs)
		md5str2:=util.EncodeMD5(string(bs))
		fmt.Println(md5str2)
		fmt.Println("C")
		retA["content"] = encrypted
		retA["sig"] = md5str2
	}
	postData,err := json.Marshal(retA)
	if err != nil {
		logging.Info(err)
	}
	return postData
}
